package com.fei.wechat.admin.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fei.wechat.common.constant.Constants;
import com.fei.wechat.middlewar.mode.vo.admin.CurrentUser;

/**
 * 描述: 后台管理用户session拦截器
 * 版权: Copyright (c) 2018 
 * 公司: 飞翔科技 
 * 作者: 张进飞 
 * 版本: 1.0 
 * 创建日期: 2018年5月20日 
 * 创建时间: 上午9:59:42
 */
public class UserSessionInterceptor extends HandlerInterceptorAdapter
{
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        HttpSession session = request.getSession();
        CurrentUser currentUser = (CurrentUser) session.getAttribute(Constants.USER_LOGIN_FLAG);
        if (null == currentUser)
        {
            // ajax请求类型
            String requestType = request.getHeader("X-Requested-With");
            if ("XMLHttpRequest".equals(requestType))
            {
                response.addHeader("sessionstatus", "timeOut");
                response.addHeader("loginPath", "/login/loginIndex?dir=1");
                response.sendError(555, "User has not login");
                return false;
            }
            else
            {
                //页面请求
                response.sendRedirect("/admin/login/index?type=1");
                return false;
            }
        }
        
        // 转移到下一个拦截器
        return super.preHandle(request, response, handler);
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception
    {
        super.postHandle(request, response, handler, modelAndView);
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception
    {
        // TODO Auto-generated method stub
        super.afterCompletion(request, response, handler, ex);
    }
}
